package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;

/**
 * 450. 删除二叉搜索树中的节点
 * 1. 找到待删除的节点
 * 2. 将待删除当前节点替换为以当前节点为根节点的树中最大的节点
 *
 * @author fy
 * @date 2022/4/26 16:18
 */
public class Solution450_1 {

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            if (root.left == null) {
                return root.right;
            }
            if (root.right == null) {
                return root.left;
            }
            // 新创建一个节点
            TreeNode p = findMax(root.left);
            TreeNode node = new TreeNode(p.val);
            node.left = root.left;
            node.right = root.right;
            node.left = deleteNode(node.left, p.val);
            return node;

            //// 另一种写法
            // TreeNode moveNode = findMax(root.left);
            // root.left = deleteNode(root.left, moveNode.val);
            // root.val = moveNode.val;
        }
        if (root.val > key) {
            root.left = deleteNode(root.left, key);
        }
        if (root.val < key) {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    private TreeNode findMax(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode node = root;
        while (node.right != null) {
            node = node.right;
        }
        return node;
    }

    public static void main(String[] args) {
        TreeNode root = BinaryTreeUtil.createTree(new Integer[]{5, 3, 6, 2, 4, null, 7});
        int key = 3;
        BinaryTreeUtil.printTree(root);

        TreeNode newRoot = new Solution450_1().deleteNode(root, key);
        BinaryTreeUtil.printTree(newRoot);
    }

}
